
// 向子组件发射事件
function broadcast (componentName, eventName, parameters) {
  // eslint-disable-next-line no-invalid-this
  for (const child of this.$children) {
    const name = child.$options.componentName
    if (name === componentName) {
      child[eventName](parameters)
    } else {
      broadcast.apply(child, [componentName, eventName, parameters])
    }
  }
}

export default {
  methods: {
    dispatch (componentName, eventName, ...parameters) {
      let parent = this.$parent || this.$root
      let name = parent.$options.componentName

      while (parent && (!name || name !== componentName)) {
        parent = parent.$parent

        if (parent) {
          name = parent.$options.componentName
        }
      }
      if (parent) {
        return parent[eventName].apply(parent, parameters)
      }
    },
    broadcast (componentName, eventName, parameters) {
      broadcast.call(this, componentName, eventName, parameters)
    },
  },
}
